package main;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class Downloader
{
	/**
	 * 
	 * @param origSt: originele str waaraan kar x keer wordt toegevoegd tot totale lengte length
	 * @param totalLength: totale lengte van gegenereerde string
	 * @param kar: karakter dat voor origSt moet gevoegd worden
	 * @return
	 */
	public String generateFixedLength(String origSt,int totalLength, String kar){
		String s=origSt;
		int currentLength=origSt.length();
		while(currentLength<totalLength){
			s = kar.concat(s);
			currentLength = s.length();
		}
		
		return s;
	}
	
	/**
	 * @param url: file die gedownloaded moet worden
	 * @param target: file waar bestand naar wordt geschreven
	 * @throws Exception
	 */
	public void downloadFile(String url, String target) throws Exception{
		try{
			BufferedInputStream in = new BufferedInputStream(new URL(url).openStream(), 8192);
	        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target), 8192);
	
	            
	        // Copy the input stream to the output stream 8k at a time.
	        final byte[] buffer = new byte[8192];
	
	        int bytes =in.read(buffer, 0, 8192); 
	        while(bytes>0){
	        	out.write(buffer, 0, bytes);
	        	bytes =in.read(buffer, 0, 8192); 
	        }
	        
	        in.close();
	        out.close();
	        
	        System.out.println("+++   " + url + " --> " + target);
		}
		catch(FileNotFoundException ex){
			System.out.println("NOT FOUND: " + url);
		}
		
	}
	
	/**
	 * 
	 * @param originalString	: originele string 
	 * @param substr			: wijzig in originalString naar substr
	 * @param startIndex		: index in originalString: tot voor deze index bestaat eerste deel
	 * @param stopIndex			: index in originalString: deze index wordt niet meer vervangen 
	 * 							  = startindex na substr, char op startindex blijft origineel 
	 * @return
	 */
	public String replaceStringAt(String originalString, String substr, int startIndex, int stopIndex){
		String str = originalString;
		String first = str.substring(0, startIndex);
		String last = str.substring(stopIndex, originalString.length());
		
		return first.concat(substr).concat(last);
	}
	/**
	 * 
	 * @param url
	 * @return bestandsnaam, gebaseerd op positie van laatste / in pad
	 */
	public String getFileName(String url){
		
		int lastSlashIndex = url.lastIndexOf("/");
		return url.substring(lastSlashIndex+1, url.length());
	}	

	public String getDirectory(String path){
		int lastSlashIndex = path.lastIndexOf("/");
		return path.substring(0, lastSlashIndex);
	}
	
	public void createDirectoryStructure(String url){
		
	}
	
	public String getPath(String url){
		int lastSlashIndex = url.indexOf("/");
		return url.substring(lastSlashIndex+1, url.length());
	}
	
	/**
	 * 
	 * @param url
	 * @param slashIndex vanaf welke slash de filename begint
	 * @return bepaalt filename
	 */
	public String getFileName(String url, int slashIndex){
		String path="";
		String tmp = url;
		for(int i=0; i<slashIndex; i++){
			
			tmp=getPath(tmp);
			
		}
		return tmp;
		
	}
	
	/**
	 * 
	 * @param original: volledig pad
	 * @param str: eerste karakter van sequence 
	 * @return index van start sequence
	 */
	public int sequenceStartIndex(String original, String str){
		
		String fileName = getFileName(original);
		
		int index = fileName.indexOf(str); 
		int startIndexFileName=original.indexOf(fileName);
		
		
		
		return index + startIndexFileName;
	}
	
	
	
	public Downloader(DownloadURL downloadUrl){
		String s = downloadUrl.getUrl();
		String firstChar = downloadUrl.getFirstCharSequence();
		
		//voor elke start - stop de lengte bepalen
		List<StartStop>list = downloadUrl.getIndices();
		for(StartStop index: list){
			
		}
		
	}
	
	public Downloader(){}
	
	public static void main(String args[]) throws IOException
	{
		Downloader t = new Downloader();
		
		String s = "http://exgfphotos.com/photo.php?pic=wp-content/Ex%20Girlfriends/ashley/2.jpg";
		
		
		System.out.println(t.getFileName(s, 3));
		
		//eerste karakter van cijferreeks die moet vervangen worden
		//vb: aa/91.jpg met foto's 92.jpg, 93.jpg, ... => CHAR="9"
		String CHAR = "2";

		//lengte van karakters die moeten vervangen worden
		//vb: aa/01.jpg met LENGTH=2: aa/02.jpg, aa/03.jpg, ... , aa/99.jpg
		int LENGTH=1;
		
		int firstIndex = t.sequenceStartIndex(s, CHAR);
		//s.indexOf(CHAR);
		int lastIndex = firstIndex+LENGTH;
		
		for(int i=1; i<10; i++){
			String sub = "" + t.generateFixedLength(i+ "", LENGTH, CHAR);
			
			String url = t.replaceStringAt(s, sub, firstIndex, lastIndex);
			try{
				t.downloadFile(url, "/Users/yannis/afb/"+t.getFileName(url));
			}
			catch(Exception ex){
				ex.printStackTrace();
			}
			
		}
		
	}
}